using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;
using UnityEngine.ResourceManagement.ResourceProviders;

namespace JEngine.Framework
{
    public class AASystem
    {
        public AASystem()
        {
        }

        public async UniTask<IList<T>> LoadAllLabels<T>(string labels, Action<T> callback = null)
        {
            var list = Addressables.LoadAssetsAsync<T>(labels, callback);
            await list;
            return list.Result;
        }


        public async UniTask<T> LoadPb<T>(string key)
        {
            var load = Addressables.LoadAssetAsync<T>(key);
            await load;
            return load.Result;
        }

        public async UniTask LoadSceneAdditive(string sceneName, Action<float> Percent)
        {
            AsyncOperationHandle<SceneInstance> sceneHandle =
                Addressables.LoadSceneAsync(sceneName, LoadSceneMode.Additive, activateOnLoad: false);

            while (!sceneHandle.IsDone)
            {
                Percent?.Invoke(sceneHandle.PercentComplete);
                await UniTask.DelayFrame(1);
            }

            SceneInstance scene = sceneHandle.Result;
            scene.ActivateAsync();
        }

        public async UniTask LoadSceneSingle(string sceneName, Action<float> Percent)
        {
            AsyncOperationHandle<SceneInstance> sceneHandle =
                Addressables.LoadSceneAsync(sceneName, LoadSceneMode.Single, activateOnLoad: true);

            while (!sceneHandle.IsDone)
            {
                Percent?.Invoke(sceneHandle.PercentComplete);
                await UniTask.DelayFrame(1);
            }

            SceneInstance scene = sceneHandle.Result;
            scene.ActivateAsync();
        }
    }
}